const requireEx=require('yi-require');

const handler = (req, res, next) => {
    // req.mongo.collection('dict').find({}).toArray((e,r)=> {
    //     let tree = BuildTree(r);
    //     SortArray(tree,"ord",1)
    //     res.reply({code:0,message:"查询成功",data:tree});
    // });
    let pname = req.query.pname;
    if(pname){
        req.mongo.collection('dict').aggregate([
            {$match:{name:pname}},
            {
                $lookup:{
                    from:"dict",
                    localField:"_id",
                    foreignField:"pid",
                    as:"childrens"
                }
            },
            {
                $unwind:"$childrens"
            },
            {
                $project:{
                    _id:"$childrens._id",
                    name:"$childrens.name",
                    val:"$childrens.val",
                    ord:"$childrens.ord",
                    pid:"$childrens.pid",
                    pname:"$name",
                    pval:"$val"
                }
            },
            {
                $sort:{
                    ord: 1
                }
            }
        ]).toArray((e,r)=>{
            if (e) return res.err.mongoError();

            res.reply({code:0,message:"查询成功",data:r});
        })
    }else {
        req.mongo.collection('dict').find({pid:null}).sort({ord:1}).toArray((e,r)=>{
            if (e) return res.err.mongoError();
            res.reply({code:0,message:"查询成功",data:r});
        });
    }

};

module.exports = {
    description:'获取字典父级',
    handler: handler
};